package com.domainlanguage.time;

import com.domainlanguage.time.TimeOfDay;
import org.hibernate.HibernateException;
import org.hibernate.type.ImmutableType;

import java.sql.*;

/**
 * Hibernate type for {@link com.domainlanguage.time.TimeOfDay}.
 *
 * Backed by {@link java.sql.Types.TIME}.
 *
 */
public class TimeOfDayType extends ImmutableType {

    @Override
    public Class getReturnedClass() {
        return TimeOfDay.class;
    }

    // TODO avoid deprecated methods on java.sql.Time

    @Override
    public Object get(ResultSet rs, String name) throws HibernateException, SQLException {
        final Time time = rs.getTime(name);
        if (time == null) {
            return null;
        }

        return TimeOfDay.hourAndMinute(time.getHours(), time.getMinutes());
    }

    @Override
    public void set(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
        final TimeOfDay timeOfDay = (TimeOfDay) value;
        st.setTime(index, new Time(timeOfDay.getHour(), timeOfDay.getMinute(), 0));
    }

    @Override
    public int sqlType() {
        return Types.TIME;
    }

    @Override
    public String toString(Object value) throws HibernateException {
        return value.toString();
    }

    @Override
    public Object fromStringValue(String xml) throws HibernateException {
        final int minute = Integer.parseInt(xml.substring(3, 5));
        final int hour = Integer.parseInt(xml.substring(0, 2));
        return TimeOfDay.hourAndMinute(hour, minute);
    }

    @Override
    public String getName() {
        return "timeOfDay";
    }

}